package com.wangzefeng.shop.security.config;

import com.wangzefeng.shop.filter.AuthFilter;
import com.wangzefeng.shop.filter.PasswordFilter;
import com.wangzefeng.shop.filter.WebSecurityCorsFilter;
import com.wangzefeng.shop.security.encoder.MD5PasswordEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;

/**
 * @author Administrator
 * @version 1.0
 **/
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- register url
            "/login/**",
            "/gateway/register/**",
            "/actuator/**"
            // other public endpoints of your API may be appended to this array
    };

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new MD5PasswordEncoder();
    }

    //安全拦截机制（最重要）
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()//permitAll代表放行
                .anyRequest().authenticated()//authenticated需要权限认证
                .and()
                .formLogin()//允许表单登录
                //.loginPage("/sys/login")//登录页面
                .loginProcessingUrl("/login")
                .and()
                .addFilter(new PasswordFilter(authenticationManager()))
                .addFilter(new AuthFilter(authenticationManager()))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .logout()
                .logoutUrl("/logout").permitAll()
                .and()
                .addFilterBefore(new WebSecurityCorsFilter(), ChannelProcessingFilter.class) // 保证跨域的过滤器首先触发

        ;

    }
}
